package de.nroz.view;

import java.awt.AWTKeyStroke;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.KeyboardFocusManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.print.CancelablePrintJob;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToggleButton;

import de.nroz.control.DBUtil;
import de.nroz.model.Artikel;
import de.nroz.model.ArtikelChangedListener;
import de.nroz.model.Images;

public class ViewArtikel
{
	private JDialog view = null;

	//	private JFrame view = new JFrame();

	private JPanel pnlMain = new JPanel();

	private JLabel lblArtnr = new JLabel("Art-Nr");

	private JLabel lblArtikel = new JLabel("Artikel");

	private JLabel lblOrt = new JLabel("Ort");

	private JLabel lblEkRPreis = new JLabel("Ek-R-Preis");

	private JLabel lblEkFaPreis = new JLabel("Ek-FA-Preis");

	private JLabel lblVkPreis = new JLabel("Vk-Preis");

	private JLabel lblEkDatum = new JLabel("Ek-Datum");

	private JLabel lblVkDatum = new JLabel("Vk-Datum");

	private JLabel lblBeschreibung = new JLabel("Beschreibung");

	private JLabel lblBezahlt = new JLabel("Bezahlt");

	private JLabel lblKanal = new JLabel("Vertriebsweg");

	private JTextField edtArtnr = new JTextField(new TextDocument(4), null, 4);

	private JTextField edtArtikel = new JTextField(new TextDocument(100), null, 60);

	private JTextField edtOrt = new JTextField(new TextDocument(2), null, 2);

	private SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yy");

	private NumberFormat nf = DecimalFormat.getNumberInstance();

	private JFormattedTextField edtEkFaPreis = new JFormattedTextField(nf);

	private JFormattedTextField edtEkRPreis = new JFormattedTextField(nf);

	private JFormattedTextField edtVkPreis = new JFormattedTextField(nf);

	private JFormattedTextField edtEkDatum = new JFormattedTextField(sdf);

	private JFormattedTextField edtVkDatum = new JFormattedTextField(sdf);

	private JTextArea edtBeschreibung = new JTextArea(new TextDocument(400));

	private JToggleButton edtBezahlt = new JToggleButton(Images.ledred);

	private JTextField edtKanal = new JTextField(20);

	private JScrollPane spBeschreibung = new JScrollPane(edtBeschreibung);

	private Artikel art = null;

	private Map<JLabel, JComponent> labelCompMap = new LinkedHashMap<JLabel, JComponent>();
	
	private WindowKeyListener keyListener = new WindowKeyListener();
	
	private JButton btnOkay = new JButton("Okay");
	
	private JButton btnCancel = new JButton("Abbrechen");
	
	private JPanel pnlButtons = new JPanel(new FlowLayout());
	
	private ArtikelChangedListener changeListener = null;
	{
		nf.setMaximumFractionDigits(2);
		nf.setMinimumFractionDigits(2);
		nf.setGroupingUsed(false);
	}

	public ViewArtikel(Frame owner, Artikel art, ArtikelChangedListener listener)
	{
		this.changeListener = listener;
		view = new JDialog(owner);
		view.setLocationRelativeTo(owner);
		this.art = art;
		initialize();
		initializeMap();
		layout();
		fillView();
	}

	private void fillView()
	{
		edtArtnr.setText(art.getArtNr());
		edtArtikel.setText(art.getArtikel());
		edtOrt.setText(art.getOrt());
		edtEkRPreis.setValue(art.getEkRPreis());
		edtEkFaPreis.setValue(art.getEkFaPreis());
		edtVkPreis.setValue(art.getVkPreis());
		edtEkDatum.setValue(art.getEkDatum());
		edtVkDatum.setValue(art.getVkDatum());
		edtBeschreibung.setText(art.getBeschreibung());
		edtBezahlt.setSelected(art.isBezahlt());
		edtKanal.setText(art.getKanal());
	}

	private void initialize()
	{
		String title;
		if (art.getArtNr() != null && art.getArtikel() != null)
		{
			title = art.getArtNr() + " " + art.getArtikel();
		}
		else
		{
			title = "Neuer Artikel";
		}
		view.setTitle(title);

		view.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

		spBeschreibung.setPreferredSize(new Dimension(700, 100));
		edtEkFaPreis.setColumns(15);
		edtEkRPreis.setColumns(15);
		edtVkPreis.setColumns(15);
		edtEkDatum.setColumns(10);
		edtVkDatum.setColumns(10);
		edtBeschreibung.setLineWrap(true);
		edtBezahlt.setSelectedIcon(Images.ledgreen);

		invertFocusTraversalBehaviour();

		view.setVisible(true);

	}

	private void initializeMap()
	{
		labelCompMap.put(lblArtnr, edtArtikel);
		labelCompMap.put(lblArtnr, edtArtnr);
		labelCompMap.put(lblArtikel, edtArtikel);
		labelCompMap.put(lblOrt, edtOrt);
		labelCompMap.put(lblEkRPreis, edtEkRPreis);
		labelCompMap.put(lblEkFaPreis, edtEkFaPreis);
		labelCompMap.put(lblVkPreis, edtVkPreis);
		labelCompMap.put(lblEkDatum, edtEkDatum);
		labelCompMap.put(lblVkDatum, edtVkDatum);
		labelCompMap.put(lblBeschreibung, spBeschreibung);
		labelCompMap.put(lblBezahlt, edtBezahlt);
		labelCompMap.put(lblKanal, edtKanal);
	}

	private void layout()
	{
		pnlMain.setLayout(new GridBagLayout());
		int yidx = 0;
		for (Entry<JLabel, JComponent> entry : labelCompMap.entrySet())
		{
			entry.getKey().setLabelFor(entry.getValue());
			entry.getValue().addKeyListener(keyListener);
			
			GridBagConstraints lblGbc = new GridBagConstraints();
			lblGbc.gridx = 0;
			lblGbc.gridy = yidx;
			lblGbc.gridheight = 1;
			lblGbc.gridwidth = 1;
			lblGbc.anchor = GridBagConstraints.WEST;
			lblGbc.insets = new Insets(0, 5, 5, 5);
			pnlMain.add(entry.getKey(), lblGbc);

			GridBagConstraints edtGbc = new GridBagConstraints();
			edtGbc.gridx = 1;
			edtGbc.gridy = yidx;
			edtGbc.gridheight = 1;
			edtGbc.gridwidth = 1;
			edtGbc.anchor = GridBagConstraints.WEST;
			edtGbc.insets = new Insets(0, 0, 5, 5);
			pnlMain.add(entry.getValue(), edtGbc);
			yidx++;
		}
		view.getContentPane().add(pnlMain, BorderLayout.CENTER);
		
		pnlButtons.add(btnOkay);
		btnOkay.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				saveAndClose();
			}
		});
		pnlButtons.add(btnCancel);
		btnCancel.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				close();
			}
		});
		view.getContentPane().add(pnlButtons, BorderLayout.SOUTH);
		
		view.pack();
	}

	private void invertFocusTraversalBehaviour()
	{
		Set<AWTKeyStroke> newForwardKeys = new HashSet<AWTKeyStroke>(1);
		newForwardKeys.add(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB, 0));
		edtBeschreibung.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, newForwardKeys);

		Set<AWTKeyStroke> newBackwardKeys = new HashSet<AWTKeyStroke>(1);
		newBackwardKeys.add(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB, KeyEvent.SHIFT_MASK + KeyEvent.SHIFT_DOWN_MASK));
		edtBeschreibung.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, newBackwardKeys);
	}
	
	private void fillArtikel()
	{
		art.setArtNr(edtArtnr.getText());
		art.setArtikel(edtArtikel.getText());
		art.setOrt(edtOrt.getText());
		art.setEkRPreis(toBigDecimal(edtEkRPreis.getValue()));
		art.setEkFaPreis(toBigDecimal(edtEkFaPreis.getValue()));
		art.setVkPreis(toBigDecimal(edtVkPreis.getValue()));
		art.setEkDatum((Date)edtEkDatum.getValue());
		art.setVkDatum((Date)edtVkDatum.getValue());
		art.setBeschreibung(edtBeschreibung.getText());
		art.setBezahlt(edtBezahlt.isSelected());
		art.setKanal(edtKanal.getText());
	}
	
	private BigDecimal toBigDecimal(Object obj)
	{
		BigDecimal retVal = null;
		if(obj instanceof Long)
		{
			retVal = BigDecimal.valueOf((Long)obj);
		}
		if(edtEkRPreis.getValue() instanceof Double)
		{
			retVal = BigDecimal.valueOf((Double)obj);
		}
		return retVal;
	}
	
	
	private void saveAndClose()
	{
		fillArtikel();
		DBUtil.getInstance().insertOrUpdate(art);
		changeListener.changedArtikel();
		view.setVisible(false);
		view.dispose();
	}
	
	private void close()
	{
		view.setVisible(false);
		view.dispose();
	}
	
	private class WindowKeyListener implements KeyListener
	{

		@Override
		public void keyPressed(KeyEvent e)
		{
		}

		@Override
		public void keyReleased(KeyEvent e)
		{
			if(e.getKeyCode() == KeyEvent.VK_ESCAPE)
			{
				close();
			} else if(e.getKeyCode() == KeyEvent.VK_CONTROL || e.getKeyCode() == KeyEvent.VK_F3)
			{
				saveAndClose();
			}
		}

		@Override
		public void keyTyped(KeyEvent e)
		{
		}
		
	}

}
